/*
 * CFile1.c
 *
 * Created: 2012-07-09 07:15:04
 *  Author: Antrykot
 */ 

#include "utils.h"

u8 save_next = 0;

void _write(u16 uiAddress, u8 ucData)
{

	while(EECR & (1<<EEPE));
	EEAR = uiAddress;
	EEDR = ucData;
	EECR |= (1<<EEMPE) ;
	EECR |= (1<<EEPE) ;

}

unsigned char _read(u16 uiAddress)
{
	while(EECR & (1<<EEPE));
	EEAR = uiAddress;
	EECR |= (1<<EERE);
	_delay_us(30);
	return EEDR;
}


double read_double(u8 addr)
{
	char dbf[4];
	
	for (u8 c = 0; c < 4; c++)
	{
		dbf[c] = _read(addr + c);
	}
	
	double *result = (double*)&dbf;
	return *result;
	
}

void write_double(u8 addr, double val)
{
	char *dbf;
	dbf = (char*)&val;
	
	for (u8 c = 0; c < 4; c++)
	{
		_write(addr + c,dbf[c]);
	}
}

void write_word(u16 addr, u16 val)
{
	char *dbf;
	dbf = (char*)&val;
	
	for (u8 c = 0; c < 2; c++)
	{
		_write(addr + c,dbf[c]);
	}
}

u16 read_word(u16 addr)
{
	char dbf[4];
	
	for (u8 c = 0; c < 2; c++)
	{
		dbf[c] = _read(addr + c);
	}
	
	u16 *result = (u16*)&dbf;
	return *result;
	
}


#define CRC8INIT    0x00
#define CRC8POLY    0x18              //0X18 = X^8+X^5+X^4+X^0

uint8_t crc8( uint8_t *data, uint16_t number_of_bytes_in_data )
{
	uint8_t  crc;
	uint16_t loop_count;
	uint8_t  bit_counter;
	uint8_t  b;
	uint8_t  feedback_bit;

	crc = CRC8INIT;

	for (loop_count = 0; loop_count != number_of_bytes_in_data; loop_count++)
	{
		b = data[loop_count];

		bit_counter = 8;
		do {
			feedback_bit = (crc ^ b) & 0x01;

			if ( feedback_bit == 0x01 ) {
				crc = crc ^ CRC8POLY;
			}
			crc = (crc >> 1) & 0x7F;
			if ( feedback_bit == 0x01 ) {
				crc = crc | 0x80;
			}

			b = b >> 1;
			bit_counter--;

		} while (bit_counter > 0);
	}

	return crc;
}

